import React, { Component } from 'react'
import { Card, Table, Button, message, Modal } from 'antd'
import LinkButton from '../../components/link-button/index'
import { PlusOutlined, RightOutlined } from '@ant-design/icons'
import { reqCategorys, reqAddCategory, reqUpdateCategory } from '../../api/index'
import AddForm from './add-form'
import UpdateForm from './update-form'

export default class Category extends Component {
	formRef = React.createRef()
	updateFormRef = React.createRef()
	state = {
		categorys: [], //一级分类列表
		subCategorys: [], //二级分类列表
		visible: false,
		loading: false,
		parentId: '0', //当前需要显示的分类列表的父分类Id
		parentName: '', //当前需要显示的分类列表的父分类名字
		showStatus: 0, //标识是添加还是编辑的弹框  0表示都不显示  1表示显示添加品类弹框,  2表示是编辑品类
	}

	// 点击查看子分类
	showSubCategorys = (record) => {
		//  setState是异步的
		this.setState(
			{
				parentId: record._id,
				parentName: record.name,
			},
			() => {
				this.getCategorys()
			}
		)
	}
	// 点击导航显示一级分类列表
	showCategory = () => {
		this.setState({
			parentId: '0',
			//   parentName: "",
			//   subCategorys:[]
		})
	}
	// 获取一级或二级分类列表
	// 如果没有传parentId根据state中的parentId请求,传了parentId就根据传的parentId请求列表
	getCategorys = async (parentId) => {
		this.setState({ loading: true })
		parentId = parentId || this.state.parentId
		const result = await reqCategorys(this.state.parentId)
		this.setState({ loading: false })
		if (result.status === 0) {
			if (this.state.parentId === '0') {
				// 获取的是一级列表
				this.setState({ categorys: result.data })
			} else {
				//获取的是二级列表
				this.setState({ subCategorys: result.data })
			}
		} else {
			message.error('获取分类列表失败')
		}
	}
	// 显示添加分类弹框
	showAdd = () => {
		this.setState({
			visible: true,
			showStatus: 1,
		})
	}

	// 显示修改分类的弹框
	showUpdate = (record) => {
		this.category = record || {} //初始化时没有点编辑按钮,record没值,会报错
		this.setState({
			showStatus: 2,
			visible: true,
		})
	}

	// 添加分类
	addCategory = () => {
		const form = this.formRef.current
		form.validateFields().then(async () => {
			const { categoryName, parentId } = form.getFieldsValue()
			const result = await reqAddCategory(categoryName, parentId)
			form.setFieldsValue({ parentId: '0', categoryName: '' })
			if (result.status === 0) {
				// 成功
				message.success('添加成功')
				this.setState({ visible: false })
				if (parentId === this.state.parentId) {
					this.getCategorys()
				} else if (parentId === '0') {
					// 在二级列表下添加一级分类,重新获取一级分类列表,但是不需要显示一级列表
					this.getCategorys('0')
				}
			} else {
				message.error('添加失败')
			}
		})
	}

	// 修改分类
	updateCategory = async () => {
		const form = this.updateFormRef.current
		form.validateFields().then(async () => {
			this.setState({
				showStatus: 0,
				visible: false,
			})
			const categoryId = this.category._id
			const { categoryName } = form.getFieldsValue()
			// 发请求编辑分类
			const result = await reqUpdateCategory({ categoryId, categoryName })
			console.log(22, result)
			// 重新获取列表
			this.getCategorys()
		})
	}

	columns = [
		{
			title: '分类名称',
			dataIndex: 'name',
		},
		{
			title: '操作',
			width: 300,
			render: (record) => (
				<span>
					<LinkButton onClick={() => this.showUpdate(record)}>修改分类</LinkButton>
					{this.state.parentId === '0' && (
						<LinkButton onClick={() => this.showSubCategorys(record)}>查看子分类</LinkButton>
					)}
				</span>
			),
		},
	]

	//弹框取消按钮
	handleCancel = () => {
		this.setState({
			visible: false,
			showStatus: '0',
		})
	}

	componentDidMount() {
		this.getCategorys()
	}
	render() {
		// Card左侧
		const title =
			this.state.parentId === '0' ? (
				'一级分类列表'
			) : (
				<span>
					<LinkButton onClick={this.showCategory}>一级分类列表</LinkButton>
					<RightOutlined style={{ marginRight: '10px' }} />
					{this.state.parentName}
				</span>
			)
		// Card右侧
		const extra = (
			<Button onClick={this.showAdd} type='primary'>
				<PlusOutlined />
				添加
			</Button>
		)
		const { categorys, subCategorys, parentId, loading, visible, showStatus } = this.state
		return (
			<div>
				<Card title={title} extra={extra}>
					<Table
						loading={loading}
						bordered
						rowKey={'_id'}
						columns={this.columns}
						pagination={{
							position: ['bottomRight'],
							size: 'small',
							defaultPageSize: 10,
							hideOnSinglePage: true,
						}}
						dataSource={parentId === '0' ? categorys : subCategorys}
					/>
					<Modal
						cancelText='取消'
						maskClosable={false}
						okText='确定'
						visible={visible}
						title={showStatus === 1 ? '添加品类' : showStatus === 2 ? '编辑品类' : ''}
						onCancel={this.handleCancel}
						onOk={showStatus === 2 ? this.updateCategory : showStatus === 1 ? this.addCategory : ''}
					>
						{showStatus === 1 && (
							<AddForm categorys={categorys} formRef={this.formRef} parentId={parentId} />
						)}
						{showStatus === 2 && (
							<UpdateForm updateFormRef={this.updateFormRef} categoryName={this.category.name} />
						)}
					</Modal>
				</Card>
			</div>
		)
	}
}
